package org.force4spring;

import java.rmi.RemoteException;

import org.apache.axis.components.logger.LogFactory;
import org.apache.commons.logging.Log;
import org.force4spring.query.QueryFactory;
import org.force4spring.support.ForceSession;
import org.force4spring.support.SessionFactory;
import org.springframework.dao.DataAccessException;

import com.sforce.soap.partner.fault.ApiFault;

public class ForceAccessor {
	private static final Log log = LogFactory.getLog(ForceAccessor.class
			.getName());
	
	private SessionFactory sessionFactory;
	
	private QueryFactory queryFactory;
	
	/**
	 * Returns value of 'sessionFactory' property
	 * 
	 * @return sessionFactory property
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Sets value of 'sessionFactory' proprty to specified value.
	
	 * @param sessionFactory New value.
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	/**
	 * Convert the given ApiFault to an appropriate exception from the
	 * <code>org.springframework.dao</code> hierarchy.
	 * <p>The default implementation delegates to SessionFactoryUtils
	 * Can be overridden in subclasses.
	 * @param fault ApiFault that occured
	 * @return the corresponding DataAccessException instance
	 * @see SessionFactoryUtils#convertApiFaultException
	 */
	public DataAccessException convertApiFault(ApiFault fault) {
		return SessionFactoryUtils.convertApiFault(fault);
	}
	
	/**
	 * Flush the given Force Session if necessary.
	 * @param session the current Force Session
	 * @param existingTransaction if executing within an existing transaction
	 * @throws ApiFault in case of Force flushing errors
	 */
	protected void flushIfNecessary(ForceSession session, boolean existingTransaction) throws ApiFault, RemoteException {
		if (!existingTransaction) {
			log.debug("Eagerly flushing Force session");
			session.flush();
		}
	}

	/**
	 * @return the queryFactory
	 */
	public QueryFactory getQueryFactory() {
		return queryFactory;
	}

	/**
	 * @param queryFactory the queryFactory to set
	 */
	public void setQueryFactory(QueryFactory queryFactory) {
		this.queryFactory = queryFactory;
	}
}
